#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# http://www.lmaye.com/

import os
import socket
import time
from files.tools import ConfigUtils

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
# 设置超时时间
timeout = 60;
clientSocket.settimeout(timeout);
# socket.setdefaulttimeout(timeout);
# 获取主机
# host = socket.gethostname();
conf = ConfigUtils(os.path.abspath("../../"));
host = conf.readConfig("server_host", section="server");
port = conf.readConfig("server_port", section="server");
clientSocket.connect((host, int(port)));
# 非阻塞模式
clientSocket.setblocking(0);

sendMsg = "Y00000001";
clientSocket.sendall(sendMsg.encode("UTF-8"));
# 信息接收
time.sleep(2);
i = 1;
msgLen = 0;
result = "";
while True:
    msg = clientSocket.recv(128);
    msgLen += len(msg);
    # print("--> %d - %s" % (len(msg), msg));
    result += msg.decode("UTF-8");
    if 1 == i:
        length = int(msg[:10]);
        i += i;
    # print("length : %d msgLen : %d" % (length, msgLen));
    if msgLen - 10 == length:
        break;
print("接收数据: \n", result[10:]);
clientSocket.close();

dataFilesPath = conf.readConfig("data_files");
if "temp" == dataFilesPath:
    dataFilesPath = os.path.abspath('../../') + conf.separator + dataFilesPath + conf.separator + time.strftime(
        "%Y-%m-%d", time.localtime());
print(dataFilesPath)
file = dataFilesPath + conf.separator + "test.xml";
# 目录不存在 - 新建目录
if False is os.path.exists(dataFilesPath):
    os.makedirs(dataFilesPath);

if os.path.exists(file):
    # 如果文件存在 - 追加
    f = open(file, "a+", encoding="UTF-8");
else:
    # 如果文件不存在 - 新增
    f = open(file, "w+", encoding="UTF-8");
f.write(result[10:]);
f.close();
